package com.qk.mangement.config;

import com.qk.common.enums.BusinessEnum;
import com.qk.common.enums.BusinessEvent;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.config.EnableStateMachineFactory;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.StateMachineFactory;
import org.springframework.statemachine.config.builders.StateMachineConfigurationConfigurer;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.listener.StateMachineListenerAdapter;
import org.springframework.statemachine.service.DefaultStateMachineService;
import org.springframework.statemachine.service.StateMachineService;
import org.springframework.statemachine.transition.Transition;

import java.util.EnumSet;

/**
 * 商机（Business）状态机配置类（独立于线索配置）
 */
@Configuration
@EnableStateMachineFactory(name = "businessStateMachineFactory") // 启用状态机工厂模式，支持多实例（每个商家一个状态机）
@Slf4j
public class BusinessStateMachineConfig extends StateMachineConfigurerAdapter<BusinessEnum, BusinessEvent> {

    // 1. 配置商机业务的所有状态（初始状态+全部状态）
    @Override
    public void configure(StateMachineStateConfigurer<BusinessEnum, BusinessEvent> states) throws Exception {
        states
                .withStates()
                .initial(BusinessEnum.WAIT_ALLOCATION) // 商家初始状态：待分配
                .states(EnumSet.allOf(BusinessEnum.class)); // 加载所有商家状态（WAIT_ALLOCATION/WAIT_TRACK等）
    }

    // 2. 配置商机状态的流转规则（核心：状态→事件→目标状态）
    @Override
    public void configure(StateMachineTransitionConfigurer<BusinessEnum, BusinessEvent> transitions) throws Exception {
        transitions
                // 规则1：待分配 + 分配事件 → 待跟进
                .withExternal()
                .source(BusinessEnum.WAIT_ALLOCATION).target(BusinessEnum.WAIT_TRACK)
                .event(BusinessEvent.ASSIGN)
                .and()
                // 规则2：待跟进 + 开始跟进事件 → 跟进中
                .withExternal()
                .source(BusinessEnum.WAIT_TRACK).target(BusinessEnum.TRACKING)
                .event(BusinessEvent.START_TRACK)
                .and()
                // 规则3：待跟进 + 回收事件 → 回收（公海）
                .withExternal()
                .source(BusinessEnum.WAIT_TRACK).target(BusinessEnum.RECOVERY)
                .event(BusinessEvent.RECOVERY)
                .and()
                // 规则4：待跟进 + 转客户事件 → 转客户
                .withExternal()
                .source(BusinessEnum.WAIT_TRACK).target(BusinessEnum.CONVERT_TO_CUSTOMER)
                .event(BusinessEvent.CONVERT_TO_CUS)
                .and()
                // 规则5：跟进中 + 回收事件 → 回收（公海）
                .withExternal()
                .source(BusinessEnum.TRACKING).target(BusinessEnum.RECOVERY)
                .event(BusinessEvent.RECOVERY)
                .and()
                // 规则：跟进中 + 转客户事件 → 转客户
                .withExternal()
                .source(BusinessEnum.TRACKING).target(BusinessEnum.CONVERT_TO_CUSTOMER)
                .event(BusinessEvent.CONVERT_TO_CUS);

    }

    // 3. 配置商机状态机监听器（监听状态变更，记录日志/触发通知）
    @Override
    public void configure(StateMachineConfigurationConfigurer<BusinessEnum, BusinessEvent> config) throws Exception {
        config
                .withConfiguration()
                .autoStartup(true) // 状态机实例创建后自动尝试启动（配合手动start兜底）
                .listener(new StateMachineListenerAdapter<BusinessEnum, BusinessEvent>() {
                    @Override
                    public void transition(Transition<BusinessEnum, BusinessEvent> transition) {
                        // 过滤初始化日志（仅记录业务触发的状态变更）
                        if (transition.getSource() != null && transition.getTarget().getId() != null) {
                            BusinessEnum from = transition.getSource().getId();
                            BusinessEnum to = transition.getTarget().getId();
                            log.info("商机状态变更：{} → {}", from, to);
                        }
                    }
                });
    }

    // 4. 定义商机状态机的Service Bean（指定Bean名，避免与线索的冲突）
    @Bean("businessStateMachineService")
    public StateMachineService<BusinessEnum, BusinessEvent> stateMachineService(
            StateMachineFactory<BusinessEnum, BusinessEvent> businessStateMachineFactory) {
        return new DefaultStateMachineService<>(businessStateMachineFactory);
    }


}